package com.edu.smsys.controller;

import com.edu.smsys.model.form.TeacherForm;
import com.edu.smsys.model.form.TeacherQueryForm;
import com.edu.smsys.model.vo.TeacherVO;
import com.edu.smsys.service.impl.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

/**
 * 老师控制器
 */
@Controller
@RequestMapping("/teacher")
public class TeacherController extends BaseController {
    @Autowired
    private TeacherService teacherService;

    /**
     * 查询所有老师信息
     *
     * @param model
     * @return
     */
    @RequestMapping("/teacherlist")
    public String teacherList(Model model) {
        //调用老师业务层读取老师信息

        //返回给页面
         List<TeacherVO> voList = teacherService.findAllVO();
         model.addAttribute("voList", voList);
        //定义到哪个视图中
        return VIEW_CONTENT + "teacher/teacheres";
    }

    /**
     * 查询所有老师信息
     * @param model
     * @param form
     * @return
     */
    @RequestMapping("/query")
    public String teacherQuery(Model model, TeacherQueryForm form){
        List<TeacherVO> voList=teacherService.findEntity(form);
        model.addAttribute("voList", voList);
        //定义到哪个视图中
        return VIEW_CONTENT + "teacher/teacheres";
    }

    /**
     * 查询所有老师信息
     *
     * @param model
     * @return
     */
    @RequestMapping("/teacherlist/json")
    @ResponseBody
    public String teacherListForJson(Model model) {
        //返回给页面
        List<TeacherVO> voList = teacherService.findAllVO();
        return toJsonStr(voList);
    }


    /**
     * 删除老师信息
     *
     * @param id 要删除的id
     * @return
     */
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id") int id) {
        teacherService.deleteEntity(id);
        return "redirect:/teacher/teacherlist";//转发到查询所有所有老师信息
    }

    /**
     * 修改老师信息
     *
     * @param teacherForm
     * @return
     */
    @RequestMapping("/update")
    public String update(TeacherForm teacherForm) {
        teacherService.updateEntity(teacherForm);
        return "redirect:/teacher/teacherlist";//转发到查询所有老师信息
    }

    /**
     * 添加老师信息页面显示
     *
     * @return
     */
    @RequestMapping("/add")
    public String add() {
        return VIEW_CONTENT + "teacher/addteacher";
    }

    /**
     * 添加老师信息执行
     *
     * @param teacherForm
     * @return
     */
    @RequestMapping("/adddo")
    public String addDo(TeacherForm teacherForm, MultipartFile file) {
        Calendar currTime = Calendar.getInstance();
        //获取时间
        String time = String.valueOf(currTime.get(Calendar.YEAR)) + String.valueOf((currTime.get(Calendar.MONTH) + 1));
        //创建图片的路径
        String path = "d:" + File.separator + "img";
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        suffix = suffix.toLowerCase();
        if (suffix.equals(".jpg") || suffix.equals(".jpeg") || suffix.equals(".png") || suffix.equals(".gif")) {
            String fileName = UUID.randomUUID().toString() + suffix;
            File targetFile = new File(path, fileName);
            if (!targetFile.getParentFile().exists()) {//注意，判断父级路径是否存在
                targetFile.getParentFile().mkdirs();
            }
            long size = 0;

            try {
                //保存
                file.transferTo(targetFile);
                //保存到数据库中把头像路径
                teacherForm.setImgSrc(fileName);//固定路径记住了！！！
                size = file.getSize();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        teacherService.addEntity(teacherForm);
        return "redirect:/teacher/teacherlist";//转发到查询所有老师信息
    }
    /**
     * 处理图片显示请求
     * @param fileName
     */
    @RequestMapping("/showPic/{fileName}.{suffix}")
    public void showPicture(@PathVariable("fileName") String fileName,
                            @PathVariable("suffix") String suffix,
                            HttpServletResponse response){
        String path = "d:" + File.separator + "img"+File.separator;
        File imgFile = new File(path+ fileName + "." + suffix);
        responseFile(response, imgFile);
    }
    /**
     * 响应输出图片文件
     * @param response
     * @param imgFile
     */
    private void responseFile(HttpServletResponse response, File imgFile) {
        try(InputStream is = new FileInputStream(imgFile);
            OutputStream os = response.getOutputStream()

        ){
            byte [] buffer = new byte[1024]; // 图片文件流缓存池
            while(is.read(buffer) != -1){
                os.write(buffer);
            }
            os.flush();
        } catch (IOException ioe){
            ioe.printStackTrace();
        }
    }
}
